<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./js/jquery.js"></script>
  </head>
  <body>
    <input type="text" placeholder="用户名" class="uname" />
    <input type="text" placeholder="密码" class="pwd" />

    <button class="login">登录</button>
    <button class="user">获取用户信息</button>
    <button class="logout">退出</button>

    <script>
      $(".login").on("click", () => {
        var uname = $(".uname").val();
        var pwd = $(".pwd").val();

        $.ajax({
          url: "http://localhost:3000/login",
          type: "post",
          data: {
            uname: uname,
            pwd: pwd,
          },
          success: (res) => {
            console.log(res);
            if (res.status == 200) localStorage.setItem("token", res.token);
          },
        });
      });

      $(".user").click(() => {
        let myToken = localStorage.getItem("token") || "";
        let token = "Bearer " + myToken;
        $.ajax({
          url: "http://localhost:3000/api/user",
          headers: {
            Authorization: token,
          },
          success: (res) => {
            console.log(res);
          },
        });
      });

      $('.logout').on('click',()=>{
        let myToken = localStorage.getItem("token") || "";
        let token = "Bearer " + myToken;

        $.ajax({
            url: "http://localhost:3000/logout",
          headers: {
            Authorization: token,
          },
          success: (res)=>{
              console.log(res);
              if(res.status == 200) {
                  localStorage.removeItem('token');
                  setTimeout(()=>{
                      window.location.href = './login.html'
                  },1000)
              }
          }
        })

      })
    </script>
  </body>
</html>
